/*
 * @Author: NtyAaron
 * @Date: 2021-04-21 18:53:18
 * @LastEditors: NtyAaron
 * @LastEditTime: 2021-04-27 13:55:38
 * @Description: file content
 * @FilePath: \dwq\pages\my\myPreference\myPreference.js
 */
import { getPreferenceList, savePreference } from '../../../api/user/user'
import { _t } from '../../../i18n/base'
Page({
  data: {
    userList: [],
    selectList: [],
    userId: '',
    language: '',
  },
  // 获取标签
  async getPreferenceList(e) {
    let { result } = await getPreferenceList({ userId: e })
    if (result) {
      let list = []
      result.map((item) => {
        if (item.preferenceId) {
          list.push(item.labelId)
        }
      })
      for (let i in result) {
        result[i].selected = list.indexOf(result[i].labelId)
      }
      this.setData({
        userList: result,
      })
    }
  },
  // 选择标签
  tagSelectHandle(e) {
    let index = e.currentTarget.dataset.index
    let item = this.data.userList[index]
    if (item.selected != -1) {
      item.selected = -1
    } else {
      item.selected = 1
    }
    this.setData({
      userList: this.data.userList,
    })
  },
  // 保存
  async tagSaveHandle() {
    let str = ''
    this.data.userList.map((item) => {
      if (item.selected != -1) {
        str += item.labelId + ','
      }
    })
    let { result } = await savePreference({
      userId: this.data.userId,
      labelIds: str,
    })
    if (result) {
      this.getPreferenceList(this.data.userId)
    }
  },
  onLoad() {
    let userId = wx.getStorageSync('userId')
    let language = wx.getStorageSync('lang')
    this.setData({
      userId,
      language,
      lang: _t(),
    })
    wx.setNavigationBarTitle({
      title: this.data.lang['推送偏好'],
    })
    this.getPreferenceList(userId)
  },
})
